# coding:utf-8
# Time    : 2019/4/16 上午10:27
# Author  : zw
# File    : cache_data.py
# Software: PyCharm
from django.core.cache import cache


def decorate_cache(cache_key, time_out=180):
    def decorate(func):
        def wrapper(*args, **kwargs):
            result = cache.get(cache_key)
            if not result:
                result = func(*args, **kwargs)
                if result:
                    cache.set(cache_key, result, time_out)
            return result

        return wrapper

    return decorate


def del_decorate_cache(cache_key):
    cache.delete(cache_key)

# 装饰器升级版本.


def decorate_cache_up(prefix, time_out=30):
    def decorate(func):
        def wrapper(*args, **kwargs):
            cache_key = prefix + str(kwargs) + (':%s' * len(args)) % (args)
            result = cache.get(cache_key)
            # print(cache_key, result)

            if result is None:
                result = func(*args, **kwargs)
                cache.set(cache_key, result, time_out)
            return result

        return wrapper

    return decorate


def del_cache_up(prefix, *args, **kwargs):
    cache_key = prefix + str(kwargs) + (':%s' * len(args)) % (args)
    cache.delete(cache_key)
    cache_key = prefix + (':%s' * len(args)) % (args)
    cache.delete(cache_key)
